require 'fileutils'

class Brand < ActiveRecord::Base
  attr_accessible :name, :status, :url, :logo, :meta_keywords, 
    :meta_description, :description, :logo_pic
  
  validates_presence_of :name
  validates_uniqueness_of :name
  
  attr_accessor :logo_pic
  
  before_save :upload_logo
  
  def to_s
    name
  end
  
  def to_param
    "#{id}-#{name}"
  end

  protected
  
    def upload_logo
      unless self.logo_pic.blank?
        FileUtils.mkdir_p(absolute_path) unless File.exist?(absolute_path)
        FileUtils.remove_file(current_full_path) if !self.new_record? and File.exist?(current_full_path)
        
        File.open(full_path, 'wb') { |f| f.write(self.logo_pic.read) }      
        self.logo = logo_url
      end
    end

    def logo_path
      'brands/logo/'
    end
  
    def absolute_path
      File.join(RAILS_ROOT, 'public', logo_path)
    end

    def logo_filename
      return logo_pic.original_filename if self.new_record?
      self.id.to_s + File.extname(logo_pic.original_filename)
    end

    def full_path
      File.join(absolute_path, logo_filename)
    end
  
    def current_full_path
      File.join(RAILS_ROOT, 'public', self.logo)
    end

    def logo_url
      logo_path + logo_filename
    end
end
